/**
 * 给定一个链表，两两交换其中相邻的节点，并返回交换后的链表。
 * <p>
 * 给定 1->2->3->4, 你应该返回 2->1->4->3.
 */
public class ListNodeOnebyOne {


    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }


        public String getValue() {
            StringBuilder sb = new StringBuilder();
            sb.append(val);
            ListNode nexts = next;
            while (nexts != null) {
                sb.append(" ").append(nexts.val);
                nexts = nexts.next;
            }

            return sb.toString();
        }
    }


    /**
     * 初始化数据
     *
     * @param n
     * @return
     */
    public ListNode initDataList(int n) {

        ListNode listNode = new ListNode(0);
        if (n < 1) {
            return listNode;
        }
        ListNode head = listNode;
        for (int i = 1; i < n; i++) {
            ListNode next = new ListNode(i);
            next.next = null;
            listNode.next = next;
            listNode = next;
        }

        return head;
    }


    public static void main(String[] args) {

        ListNode prd = new ListNodeOnebyOne().initDataList(4);


        prd = nodeChange(prd);


        System.out.println(prd.getValue());

    }

    public static ListNode nodeChange2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode first = head;
        head = first.next;
        ListNode second;
        ListNode trd;
        ListNode prd=null;

        while (first != null && first.next != null) {
            second = first.next;//第二个
            trd = second.next;//后续个
            second.next = first;//二后链接一
            if (prd != null) {
                prd.next = second;
            }
            first.next = trd;//一后链接后续
            prd = first;
            first = trd;
        }

        return head;
    }


    /**
     * 当前节点的位置
     *
     * @return
     */
    public static ListNode nodeChange(ListNode head) {
        if (head == null || head.next == null) {

            return head;
        }
        ListNode first = head;
        ListNode second = head.next;//第二个
        ListNode trd = second.next;
        second.next = first;//第二个和第一个连接
        first.next = nodeChange(trd);//第三个


        return second;
    }


}
